<template>
    <el-form class="address-form" :model="form" :rules="formRules" ref="form" autocomplete="off" @submit.native.stop="doSubmit($event)">

        <el-form-item label="Full name" prop="first_name">
            <el-input size="small" autocomplete="off" v-model="form.first_name"></el-input>
        </el-form-item>

        <div style="width: 100%"></div>
        <el-form-item label="Phone" prop="phone">
            <el-input size="small" v-model="form.phone"></el-input>
        </el-form-item>

        <el-form-item label="Email (optional)" prop="email">
            <el-input size="small" v-model="form.email"></el-input>
        </el-form-item>

        <el-form-item label="Address line 1" prop="street">
            <el-input size="small" v-model="form.street"></el-input>
        </el-form-item>

        <el-form-item label="Address line 2 (optional)" prop="district">
            <el-input size="small" v-model="form.district"></el-input>
        </el-form-item>

        <el-form-item label="Country/Region" prop="country">
            <el-select size="small" v-model="form.country" placeholder="Please select" @change="changeCountry" filterable>
                <el-option v-for="item in country" :key="item.name" :label="item.name" :value="item.name"></el-option>
            </el-select>
        </el-form-item>
        <div style="width: 100%"></div>

        <el-form-item v-if="activeStates.length > 0" label="State/Province" prop="state">
            <el-select size="small" v-model="form.state" placeholder="Please select state" filterable>
                <el-option v-for="item in activeStates" :key="item.name" :label="item.name" :value="item.name"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="State/Province (optional)" prop="state" v-else>
            <el-input size="small" v-model="form.state"></el-input>
        </el-form-item>

        <div style="width: 100%"></div>

        <el-form-item label="City" prop="city" style="width: 25%; padding-right: 20px">
            <el-input size="small" v-model="form.city"></el-input>
        </el-form-item>

        <el-form-item label="Postal/ZIP code" prop="post_code" style="width: 25%; padding-left: 0px">
            <el-input size="small" autocomplete="on" v-model="form.post_code"></el-input>
        </el-form-item>
    </el-form>
</template>
<script>
import { getRules } from "@/utils/address-rules";
import AsyncValidator from 'async-validator';
// import Country from "@/utils/country";

import { mapGetters } from "vuex";
export default {
    name: "AddressForm",
    props: {
        value: { type: Object, default: () => null },
        rules: { type: Object, default: () => null },
    },
    data () {
        return {
            // country: Country, // 地区
            country: [], // 地区
            states: [],
            // rules: getRules(),
            form: {
                id: '',
                first_name: '', // string 姓名
                country_code: '', // string 国家（国际二字码 标准ISO 3166-2 ）
                country: '', // string 国家名称
                city: '', // string 城市
                state: '', // string  州/省
                district: '', // string 区、县（可对应为adress 2）
                street: '', // string 街道/详细地址（可对应为adress 1）
                email: '', // string 邮箱
                phone: '', // string 电话
                post_code: '', // string 邮编
            }
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        activeStates () {
            return this.states.filter(i => i.country == this.form.country_code)
        },
        initRules () {
            return this.rules || getRules() || {};
        },
        formRules () {
            const rules = this.initRules;
            const state = rules.state || [];
            if (this.activeStates && this.activeStates.length > 0) {
                state.map(item => {
                    if (item.hasOwnProperty('required')) {
                        item.required = true;
                    }
                })
            } else {
                state.map(item => {
                    if (item.hasOwnProperty('required')) {
                        item.required = false;
                    }
                })
            }
            return rules;
        },

    },
    watch: {
        form: {
            deep: true,
            handler (newval) {
                this.$emit('input', newval)
                this.silenceValidator();
            }
        },
        value: {
            deep: true,
            immediate: true,
            handler (newval) {
                const addr = newval || {};
                Object.keys(this.form).map(key => {
                    if (this.form[key] !== addr[key]) {
                        this.form[key] = addr[key]
                    }
                });
            }
        }
    },
    methods: {
        getCountris () {

            const userInfo = this.userInfo || {}

            const doInit = (option) => {

                this.country = option.countries || []
                this.states = option.states || [];

                // 初始化
                // 如果没有选择国家，则默认选择一个
                if (userInfo.country_iso_name && !this.form.country) {
                    const active = this.country.filter(i => i.id == userInfo.country_iso_name)[0];
                    if (active) {
                        this.form.country = active.name;
                        this.changeCountry(this.form.country);
                    }
                }
            }

            if (window._CITY) {
                doInit(window._CITY)
            } else {
                this.$http('Resource.countris').then(response => {
                    if (response && response.countries && response.states) {
                        window._CITY = response;
                        doInit(response);
                    }
                }).catch(error => {
                    this.$uxMessage.warning('Failed to get address list');
                });
            }
        },

        // 静默表单验证
        silenceValidator () {
            this.$nextTick(e => {
                const descriptor = {}
                const address = this.form || {};
                const rules = this.formRules || {}

                Object.keys(address).map(key => rules[key] && (descriptor[key] = rules[key]));
                (new AsyncValidator(descriptor)).validate(address, { suppressWarning: true }, (err, fields) => {
                    this.$emit('validate', err && err.length > 0);
                })
            })
        },
        // 有提示的认证
        tipsValidator () {

            if (this.$refs.form) {
                return this.$refs.form.validate();
            } else {
                return Promise.reject('no address form')
            }
        },
        // 修改地址
        changeCountry (name) {
            let select = this.country.filter((i) => i.name == name)[0];
            if (select) {
                this.form.country_code = select.id;
                if (this.form.state) {
                    const state = this.states.filter(i => i.country == select.id && this.form.state == i.name);
                    state.length == 0 && (this.form.state = '');
                }
            }
        },

        // 提交
        doSubmit (event) {

            event.preventDefault();
            event.stopPropagation();

            this.tipsValidator().then(() => {
                this.$email('submit', this.form);
            }).catch((err) => {
                this.$uxMessage.error("The address is incorrect, please check completely and try again");
            });
        }
    },
    created () {
        this.getCountris()
        // Resource
        // this.silenceValidator();
    }
};
</script>
<style lang="scss" scoped>
.address-form ::v-deep {
    position: relative;
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
        width: 50%;
        box-sizing: border-box;
        padding: 0 24px;
    }

    .el-form-item {
        margin-bottom: 26px;
    }

    .el-form-item__content {
        line-height: 32px;
        vertical-align: top;
    }

    .el-form-item__label {
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 16px;
        margin-bottom: 8px;
        &::before {
            display: none !important;
        }
    }

    .el-form-item__error {
        word-break: normal;
        position: absolute;
        left: 0px;
        pointer-events: none;
        top: 100%;
        margin-top: 0;
        bottom: 0;
        white-space: nowrap;
        font-size: 12px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #940306;
        line-height: 14px;
        // line-height: 32px;
    }

    .el-input {
        .el-input__inner {
            height: 36px;
            font-size: 14px;
            border-color: #e6e6e6;
            color: #000;
            border-radius: 8px;

            &:hover {
                border-color: #c7c7c7;
                box-shadow: initial;
            }

            &:active,
            &:focus {
                border-color: #f6b2cd;
                box-shadow: 0 0 1px 1px #f6b2cd;
            }
        }
    }

    .el-select {
        width: 100%;
        .el-input__inner {
            height: 36px;
            font-size: 14px;
            border-color: #e6e6e6;
            color: #000;
            border-radius: 8px;

            &:hover {
                border-color: #c7c7c7;
                box-shadow: initial;
            }

            &:active,
            &:focus {
                border-color: #f6b2cd;
                box-shadow: 0 0 1px 1px #f6b2cd;
            }
        }
    }

    h6 {
        margin: 44px 24px 0 auto;
        height: 18px;
        font-size: 16px;

        color: #000000;
        line-height: 18px;
        font-weight: normal;
        cursor: pointer;
        text-decoration: underline;

        &:hover {
            color: #ea4c89;
        }
    }

    .form-button {
        margin-top: 20px;
        width: 100%;
        display: flex;
        justify-content: center;

        button {
            margin: 0 20px;
            width: 160px;
            height: 34px;
        }
    }
}
</style>
